Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

drupal-jsonapi-params

Package Overview
Dependencies
Maintainers
0
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

drupal-jsonapi-params

Drupal JSON-API params

  • 2.3.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Drupal JSON-API Params

GitHub pages build status Codecov npm npm package minimized gzipped size npm type definitions npm downloads

The JSON:API is part of Drupal Core.

The JSON:API specifications defines standard query parameters to be used to do filtering, sorting, restricting fields that are returned, pagination and so on.

This module provides a helper Class to create the required query. While doing so, it also tries to optimise the query by using the short form, whenever possible.

API Reference

Installation

Install the package via npm:

$ npm i drupal-jsonapi-params

Usage

import

Import DrupalJsonApiParams from drupal-jsonapi-params

import {DrupalJsonApiParams} from 'drupal-jsonapi-params';

const apiParams = new DrupalJsonApiParams();

require

var drupalJsonapiParams = require("drupal-jsonapi-params")

const apiParams = new drupalJsonapiParams.DrupalJsonApiParams();
apiParams
  // Add Group within Groups.
  .addGroup('publish_status', 'OR', 'parent_group')
  .addGroup('child_group_B', 'AND', 'parent_group')
  .addGroup('parent_group', 'AND')
  // Add Filters.
  .addFilter('status', '1')
  // Add Filter to Group.
  .addFilter('status', '2', '!=', 'publish_status')
  // Add Page Limit.
  .addPageLimit(5)
  // Add Page Offset.
  .addPageOffset(20)
  // Add Fields.
  .addFields('node--article', ['field_a.id', 'field_b.uid', 'field_c.tid'])
  // Add Includes.
  .addInclude(['field_a.id', 'field_b.uid', 'field_c.tid'])
  // Add multiple sort criterion.
  .addSort('id', 'DESC')
  .addSort('uid')
  .addSort('status');

const urlencodedQueryString = apiParams.getQueryString();
const queryString = apiParams.getQueryString({ encode: false });

API

getQueryString [options?]

Returns query string which can be used in api calls. By default the output is URI encoded. Options can be passed to control the qs.stringifying internally used.

addFilter

Used to restrict items returned in a listing.

ParamsTypeDescription
pathstringA 'path' identifies a field on a resource
valuestringstring[]
operatorstring(Optional) An 'operator' is a method of comparison
groupstring(Optional) Name of the group, the filter belongs to

Following values can be used for the operator. If none is provided, it assumes "=" by default.

  '=', '<>',
  '>', '>=', '<', '<=',
  'STARTS_WITH', 'CONTAINS', 'ENDS_WITH',
  'IN', 'NOT IN',
  'BETWEEN', 'NOT BETWEEN',
  'IS NULL', 'IS NOT NULL'

NOTE: Make sure you match the value supplied based on the operators used as per the table below

Value TypeOperatorDescription
string=, <>, >, >=, <, <=, STARTS_WITH, CONTAINS, ENDS_WITH
string[]IN, NOT IN
string[] size 2BETWEEN, NOT BETWEENThe first item is used for min (start of the range), and the second item is used for max (end of the range).
nullIS NULL, IS NOT NULLMust use null

Read more about filter in Drupal.org Documentation

addGroup

Used to group Filters. Groups can be nested too.

ParamsTypeDescription
namestringName of the group
conjunctionstring(Optional) All groups have conjunctions and a conjunction is either AND or OR.
memberOfstring(Optional) Name of the group, this group belongs to

addInclude

Used to add referenced resources inside same request. Thereby preventing additional api calls.

ParamsTypeDescription
fieldsstring[]Array of field names

Read more about Includes in Drupal.org Documentation

addSort

Used to return the list of items in specific order.

ParamsTypeDescription
pathstringA 'path' identifies a field on a resource
directionstringSort direction ASC or DESC

Read more about Sort in Drupal.org Documentation

addPageLimit

Use to restrict max amount of items returned in the listing. Using this for pagination is tricky, and make sure you read the following document on Drupal.org to implement it correctly.

ParamsTypeDescription
limitnumberNumber of items to limit to

Read more about Pagination in Drupal.org Documentation

addPageOffset

Use to skip some items items from start of the listing. Please note that this is not the page number. To get the offset number for a page you can multiply the number of pages you want to skip with items per page.

ParamsTypeDescription
offsetnumberNumber of items to skip to

Read more about Pagination in Drupal.org Documentation

NOTE

JSON:API response have pagination information build into the response. Based on the results in the response, you can get "previous" and "next" links which can be used to get further items when results overflows into multiple pages.

If you are looking for a practical guide, you can check out the example in this issue on GitHub https://github.com/d34dman/drupal-jsonapi-params/issues/40

addFields

The name of this method might be misleading. Use this to explicitely request for specific fields on an entity.

ParamsTypeDescription
typestringResource type
fieldsstring[]Array of field names in the given resource type

addCustomParam

Use to add custom parameter to the query.

ParamsTypeDescription
inputobjectThe parameter object

E.g. usage

apiParams
  // To add `foo=bar` to the query.
  .addCustomParam({foo: 'bar'})
  // To add `foo[bar]=baz` to the query.
  .addCustomParam({ foo: {bar: 'baz'}})
  // To add `bar[0]=a&bar[1]=b&bar[2]=c` to the query.
  .addCustomParam({ bar: ['a', 'b', 'c']})

Helper methods

clear

Clears all query parameter constructed so far.

getQueryObject

Get object representation of the query object generated so far.

initialize

Re-initialize with a query string/object or another instance of DrupalJsonApiParams

initializeWithQueryObject

Re-initialize with previously stored data from getQueryObject

initializeWithQueryString

Re-initialize with previously stored data from getQueryString. This method accepts an optional parameter to pass options to qs library when parsing the given query.

Please refer to https://www.npmjs.com/package/qs for more info about available options.

This would override any options set using setQsOptions during the given call.

setQsOption

Set options that is passed to qs library when parsing/serializing query paramters. Please refer to https://www.npmjs.com/package/qs for more info about available options.

getQsOption

Get options that is passed to qs library when parsing/serializing query paramters. The value should match whatever was previously set via setQsOptions method.

Keywords

FAQs

Package last updated on 18 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc